<?php
namespace app\admin\controller;

use app\admin\model\CollectLog;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\user\model\User;
use app\common\controller\AdminController;
use app\common\model\Article;
use think\App;
use think\facade\Env;
use think\facade\Db;

class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch('', [
            'admin' => session('admin'),
        ]);
    }

    /**
     * 后台欢迎页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        //用户总数
        $userCount=(new User())->count();
        $articleCount=(new Article())->count();
        $userToday=(new User())->where('create_time','>',todayTime())->count();
        $articleToday=(new Article())->where('create_time','>',todayTime())->count();
        $articleCollectToday=(new CollectLog())->where('create_time','>',todayTime())->count();
        $articleNoCheck=(new Article())->where('status',0)->count();
        $quicks = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])
            ->order('sort', 'desc')
            ->limit(8)
            ->select();
        $this->assign('count', [
            'user'=>$userCount,
            'article_nocheck'=>$articleNoCheck,
            'article'=>$articleCount,
        ]);
        $this->assign('today', [
            'user'=>$userToday,
            'article'=>$articleToday,
            'article_collect'=>$articleCollectToday,
        ]);
        $this->assign('quicks', $quicks);
        return $this->fetch();
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $this->isDemo && $this->error('演示环境下不允许修改');
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            // 判断是否为演示站点
            $example = Env::get('laysns.IS_DEMO', 0);
            $example == 1 && $this->error('演示站点不允许修改密码');

            try {
                if($row->user_id>0){
                    $user=(new User())->where('id',$row->user_id)->find();
                    $save = $user->save([
                        'password' => md5($post['password'] . $user['salt'])
                    ]);
                }else {
                    $save = $row->save([
                        'password' => password($post['password']),
                    ]);
                }
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    public function toggle()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $id=$params['id'];
            $status=$params['status'];
            $name=$params['name'];
            $table = $params['table'];
            if (Db::name($table)->where('id', $id)->update([$name => $status]) !== false) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
    }
}
